/**
 * @author Jiange
 * @create 2021-05-12-14:45
 */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 多线程交互中必须要避免多线程的虚假唤醒  要使用while 这样可以使它被唤醒的时候还是会被检验的
 */
class Demo{
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

//    public synchronized void increment() throws InterruptedException {
//        while (number != 0){
//            this.wait();
//        }
//        number++;
//        System.out.println(Thread.currentThread().getName()+"\t"+number);
//        this.notifyAll();
//    }

    public void increment(){
        lock.lock();
        try{
            while (number != 0){
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void decrement(){
        lock.lock();
        try{
            while (number == 0){
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

//    public synchronized void decrement() throws InterruptedException {
//        while (number ==0 ){
//            this.wait();
//        }
//
//        number--;
//        System.out.println(Thread.currentThread().getName()+"\t"+number);
//        this.notifyAll();
//    }
}

public class ThreadWait {
    public static void main(String[] args) {
        Demo demo = new Demo();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                demo.increment();
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                demo.decrement();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                demo.decrement();
            }
        },"D").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                demo.increment();
            }
        },"C").start();
    }
}
